package com.example.statistics.ex

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Build
import androidx.core.content.FileProvider
import androidx.fragment.app.FragmentActivity
import com.example.statistics.BuildConfig
import com.example.statistics.bean.FilesBean
import com.example.statistics.common.MultiSelectListActivity
import com.example.statistics.net.callback.DownloadDialogHttpCallback
import com.example.statistics.utils.Constants
import com.example.statistics.utils.FileUtils
import com.example.statistics.utils.activityForResult
import com.example.statistics.utils.file.fileSuffix
import com.example.statistics.utils.permissions.PermissionsCheck
import com.jhj.httplibrary.HttpCall
import org.jetbrains.anko.toast
import java.io.File
import java.net.URLDecoder

fun Activity.tell(phone: String) {
    val intent = Intent(Intent.ACTION_DIAL)
    intent.data = Uri.parse("tel:$phone")
    startActivity(intent)
}

inline fun <reified T> FragmentActivity.mu(
    title: String,
    url: String,
    t: T,
    selectedIdList: List<Int>,
    crossinline body: (Intent?) -> Unit
) {
    activityForResult<MultiSelectListActivity>(
        Constants.TITLE to title,
        Constants.TYPE to t,
        Constants.PATH to url,
        Constants.DATA to selectedIdList
    ) { intent ->
        body(intent)
    }
}

fun Activity.permission(vararg permissions: String) {
    PermissionsCheck.with(this)
        .requestPermissions(*permissions)
        .onPermissionsResult { strings, strings2 ->

        }
}


fun Activity.download(fileBean: FilesBean, body: (File) -> Unit) {
    PermissionsCheck.with(this)
        .requestPermissions(
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        )
        .onPermissionsResult { _, _ ->
            val path = fileBean.path.replace("/upload", "")
            val lastIndexOf = path.lastIndexOf("/")
            val folder: String? = FileUtils.getSDPath(path.substring(0, lastIndexOf))
            var localPath = folder + "/" + fileBean.name
            localPath = URLDecoder.decode(localPath, "utf-8")
            val localFile = File(localPath)
            if (localFile.exists() && localFile.length() >= fileBean.size) {
                body(localFile)
            } else {
                localFile.createNewFile()
                HttpCall.download(HttpCall.baseUrl + fileBean.path)
                    .setUseBaseUrl(false)
                    .enqueue(object : DownloadDialogHttpCallback(this, localFile, "加载中...") {
                        override fun onSuccess(file: File) {
                            body(localFile)
                        }

                        override fun onFailure(msg: String) {
                            toast(msg)
                            if (localFile.exists()) {
                                localFile.delete()
                            }
                        }
                    })
            }
        }

}

fun Activity.openFile(fileBean: FilesBean) {
    download(fileBean) { file ->
        val intent = Intent("android.intent.action.VIEW")
        intent.addCategory("android.intent.category.DEFAULT")
        val authority = BuildConfig.APPLICATION_ID + ".provider.LibFileProvider"
        val uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            FileProvider.getUriForFile(this, authority, file)
        } else {
            Uri.fromFile(file)
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        try {
            val a = when (file.path.fileSuffix) {
                ".doc" -> {
                    "application/msword"
                }
                ".xls", ".xlsx" -> {
                    "application/vnd.ms-excel"
                }
                ".ppt" -> {
                    "application/vnd.ms-powerpoint"
                }
                ".pdf" -> {
                    "application/pdf"
                }
                else -> {
                    ""
                }
            }
            intent.setDataAndType(uri, a)
            startActivity(intent)
        } catch (e: Exception) {
            toast("没有找到打开该文件的应用程序")
        }
    }
}
